﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using CarErp.Data;
using System.Data.Entity.Migrations;
using CarErp.Forms;
using CarErp.Model;

namespace CarErp
{
	static class Program
	{
		/// <summary>
		/// 应用程序的主入口点。
		/// </summary>
		[STAThread]
		static void Main()
		{
			var context = new CarERPContext();
			InitialDatabase(context);
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);

			var login = new LoginForm();
			login.FormClosing += Exit;
			login.OnLogin += (username, password) =>
			  {
				  var user = context.Users.FirstOrDefault(x => x.Name == username && x.Password == password);
				  if (user == null)
				  {
					  MessageBox.Show("用户名或密码错误");
					  return;
				  }
				  login.FormClosing -= Exit;
				  login.Close();
				  EnterApp(user, context);
			  };
			login.Show();

			Application.Run();
		}

		static void EnterApp(User user, CarERPContext context)
		{
			switch (user.Role)
			{
				case Role.Submitter:
					EnterSubmitter(user, context);
					break;
				case Role.Approver:
					EnterApprover(user, context);
					break;
			}
		}

		static void EnterSubmitter(User user, CarERPContext context)
		{
			var subimtForm = new NewApplicationForm(user);
			subimtForm.FormClosing += Exit;
			subimtForm.OnApplicationCreated += newApp =>
			  {
				  context.CarPurchaseApplications.Add(newApp);
				  context.SaveChanges();
				  MessageBox.Show("提交成功");
			  };
			subimtForm.Show();
		}

		static void EnterApprover(User user, CarERPContext context)
		{
			var form = new ApplicationViewForm(context, user);
			form.FormClosing += Exit;
			form.Show();
		}

		static void InitialDatabase(CarERPContext context)
		{
			if (!context.Database.Exists())
			{
				var config = new Migrations.Configuration();
				var migrator = new DbMigrator(config);
				migrator.Update();
			}
		}

		static void Exit(object sender, FormClosingEventArgs e) => Application.Exit();
	}
}
